package com.cash.app.ui.start

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.webkit.WebView
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.custom.AppActionBar
import com.cash.app.databinding.AcPolicyBinding
import android.webkit.WebViewClient
import android.view.ViewTreeObserver

class PolicyActivity : BaseActivity() {

    companion object {
        const val EXTRA_SHOW_BOTTOM = "extra_show_bottom"
    }

    private lateinit var binding: AcPolicyBinding
    private lateinit var webView: WebView
    private lateinit var checkboxAgree: CheckBox
    private lateinit var btnReject: TextView
    private lateinit var btnNext: TextView

    private var hasScrolledToBottom = false
    private var scrollListener: ViewTreeObserver.OnScrollChangedListener? = null

    override fun setViewBind() {
        binding = AcPolicyBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun getAppActionBar(): AppActionBar? {
        return binding.actionBar
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        setupWebView()
        handleBottomVisibility()
    }

    private fun handleBottomVisibility() {
        val showBottom = intent.getBooleanExtra(EXTRA_SHOW_BOTTOM, true)
        binding.bottomCl.visibility = if (showBottom) View.VISIBLE else View.GONE
    }

    private fun initView() {
        webView = binding.webView
        checkboxAgree = binding.checkboxAgree
        btnReject = binding.btnReject
        btnNext = binding.btnNext

        btnReject.setOnClickListener {
            finish()
        }

        btnNext.setOnClickListener {
            if (hasScrolledToBottom) {
                if (!checkboxAgree.isChecked) {
                    toast(getString(R.string.policy_not_agree))
                    return@setOnClickListener
                }
                startActivity(Intent(this, PermissionActivity::class.java))
                finish()
            } else {
                // Implement smooth scroll to bottom
                webView.post {
                    val webViewHeight = webView.height
                    val contentHeight = (webView.contentHeight * webView.scale).toInt()
                    val maxScrollY = contentHeight - webViewHeight

                    if (maxScrollY > 0) {
                        webView.scrollTo(0, maxScrollY)
                        // Update scroll state after animation completes
                        webView.postDelayed({
                            updateScrollState(true)
                        }, 500) // Wait for scroll animation
                    } else {
                        // If content is not scrollable, consider it as scrolled to bottom
                        updateScrollState(true)
                    }
                }
            }
        }
    }

    private fun setupWebView() {
        webView.settings.javaScriptEnabled = false
        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                setupScrollListener()
                btnNext.text = getString(R.string.btn_next)
            }
        }
        webView.loadUrl("file:///android_asset/privacy.html")
    }

    private fun setupScrollListener() {
        // Remove existing listener if any
        scrollListener?.let {
            webView.viewTreeObserver.removeOnScrollChangedListener(it)
        }

        // Create and set new scroll listener
        scrollListener = ViewTreeObserver.OnScrollChangedListener {
            val webViewHeight = webView.height
            val contentHeight = (webView.contentHeight * webView.scale).toInt()
            val scrollY = webView.scrollY
            val maxScrollY = contentHeight - webViewHeight

            // Consider scrolled to bottom if within 50 pixels or at max scroll position
            val isAtBottom = (maxScrollY - scrollY) <= 50 || scrollY >= maxScrollY

            if (isAtBottom != hasScrolledToBottom) {
                updateScrollState(isAtBottom)
            }
        }

        // Add the new listener
        webView.viewTreeObserver.addOnScrollChangedListener(scrollListener)
    }

    private fun updateScrollState(isAtBottom: Boolean) {
        hasScrolledToBottom = isAtBottom
        btnNext.text = getString(if (isAtBottom) R.string.btn_agree else R.string.btn_next)
    }

    private fun toast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        // Clean up scroll listener
        scrollListener?.let {
            webView.viewTreeObserver.removeOnScrollChangedListener(it)
        }
    }
} 